#ifndef DRIVERCONTROLLER_H
#define DRIVERCONTROLLER_H

#include "DriverManager.h"

#include <QObject>
#include <QAbstractItemModel>
#include <QSet>

struct PortPair {
    PortPair(const DeviceInfo *busDev)
        : m_pairNum(-1)
        , m_busDevice(busDev)
        , m_portA(nullptr)
        , m_portB(nullptr)
    {
        m_pairNum = m_busDevice->portPair.split("_").last().toInt();
    }

    const DeviceInfo* busDevice()   const { return m_busDevice; }
    const DeviceInfo* portA()       const { return m_portA; }
    const DeviceInfo* portB()       const { return m_portB; }
    const int         pairNum()     const { return m_pairNum; }
    void setPortA(const DeviceInfo *port) { m_portA = port; }
    void setPortB(const DeviceInfo *port) { m_portB = port; }

private:
    int m_pairNum;
    const DeviceInfo* m_busDevice;
    const DeviceInfo* m_portA;
    const DeviceInfo* m_portB;
};

enum ControlPortType {
    ROUTINE_PORT,
    INPUT_PORT,
    ENDPOINT_PORT,
};

class PortDeviceModel : public QAbstractItemModel
{
    /**
     * InternalId Format (stable)
     * quintptr [ pointer to PortPair with 2 low bits as typeFlag ]
     * [    PortPair* aligned    |  2bit typeFlag ]
     * typeFlag: 0->Bus, 1->PortA, 2->PortB
     * Do NOT encode row in id (rows shift on insert/remove).
     **/

    Q_OBJECT
public:
    PortDeviceModel(QObject *parent = nullptr);
    ~PortDeviceModel();

public:
    // QAbstractItemModel interface
    virtual QModelIndex index(int row, int column, const QModelIndex &parent) const override;
    virtual QModelIndex parent(const QModelIndex &child) const override;
    virtual int rowCount(const QModelIndex &parent) const override;
    virtual int columnCount(const QModelIndex &parent) const override;
    virtual QVariant data(const QModelIndex &index, int role) const override;
    virtual QVariant headerData(int section, Qt::Orientation orientation, int role) const override;
    // drag
    QStringList mimeTypes() const override;
    QMimeData *mimeData(const QModelIndexList &indexes) const override;
    Qt::ItemFlags flags(const QModelIndex &index) const override;

    // 获取串口对数据
    static const PortPair* getPairInfo(QModelIndex idx);
    // 是否输出端口
    static const bool isEndPoint(const QString& portName);
    // 从端口名获取端口对
    static const PortPair* getPairFromPortName(const QString& portName);

    // 端点选择状态（用于视图显示状态灯）
    void setInputSelected(const QString &portName);
    void setEndpointSelected(const QString &portName, bool selected);

    // 内存管理接口
    void takeOwnership(QVector<PortPair*>&& portPairs);
    void clearData();

public slots:
    void deviceFoundHandle(const DeviceInfo &info);
    void deviceRemovedHandle(const DeviceInfo &info);

private:
    static QString             sm_inputPortName;
    static QVector<PortPair*> sm_portPairs;
    static QSet<QString> sm_endpointPorts; // 已加入 endpoints 的端口名集合
};

class DriverController : public QObject
{
    Q_OBJECT
public:
    explicit DriverController(QObject *parent = nullptr);
    ~DriverController();

    void initialize();

    PortDeviceModel* getPortDeviceModel() { return m_portDeviceModel; }

    // 更新端点选择状态（驱动模型中用于显示状态灯）
    void setInputSelected(const QString &portName);
    void setEndpointSelected(const QString &portName, bool selected);

signals:
    /**
     * @brief 创建串口对信号 - DeviceController
     */
    void createPortPairSignal();

    /**
     * @brief 删除串口对信号 - DeviceController
     */
    void removedPortPairSignal(int num);

public slots:
    void refreshVirtualPortList();

    void buildDeviceTree();

private:
    DriverManager       *m_driverManager      = nullptr;
    PortDeviceModel     *m_portDeviceModel    = nullptr;
};

#endif // DRIVERCONTROLLER_H
